<?php
require '../data/data.php';
session_start();

$username = isset($_POST['username'])?htmlspecialchars($_POST['username']):'';
$password = isset($_POST['password'])?htmlspecialchars($_POST['password']):'';
$pwd_again = isset($_POST['pwd_again'])?htmlspecialchars($_POST['pwd_again']):'';
$code = isset($_POST['code'])?htmlspecialchars($_POST['code']) :'';

$hasError = false;
$inputBag = ['username' => $username];
$errorBag = ['username'=>'','password'=>'','pwd_again'=>'','code'=>''];

if (trim($username) == '') {
	$hasError = true;
	$errorBag['username'] = '用户名不能为空';
}elseif (strlen($password) < 6) {
	$hasError = true;
	$errorBag['password'] = '密码必须大于6位';
}elseif ($pwd_again !== $password) {
	$hasError = true;
	$errorBag['pwd_again'] = '两次输入的密码必须一致';
}elseif (trim($code) == '') {
	$hasError = true;
	$errorBag['code'] = '验证码不能为空';
}elseif ($code != $_SESSION['code']) {
	$hasError = true;
	$errorBag['code'] = '验证码错误';
}else{
    $sql = 'select id from users where user_name=?';
    $data = query($sql,[$username]);
    if (count($data)>0) {
	    $hasError = true;
	    echo "用户已存在";$errorBag['username'] = '用户已存在';
    }
}
$_SESSION['has_error'] = $hasError;
$_SESSION['error_bag'] = $errorBag;
$_SESSION['input_bag'] = $inputBag;
if($hasError){
	header('Location:../public/register.php');
	return;
}

$password = password_hash($password,PASSWORD_BCRYPT);
$sql = 'insert into users(user_name,password,register_time) values(?,?,now())';
$args = [$username,$password];
if(execute($sql,$args)){
	header('Location:../public/signin.php');
}else{
	header('Location:../public/register.php');
}